package org.ss.util;

import cn.hutool.extra.spring.SpringUtil;
import com.auth0.jwt.JWT;
import com.auth0.jwt.JWTCreator;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.exceptions.AlgorithmMismatchException;
import com.auth0.jwt.exceptions.SignatureVerificationException;
import com.auth0.jwt.exceptions.TokenExpiredException;
import com.auth0.jwt.interfaces.DecodedJWT;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.ss.config.JwtConfig;

import java.util.Calendar;
import java.util.HashMap;
import java.util.Map;

public class JwtUtil {

    public static Logger logger = LoggerFactory.getLogger(JwtUtil.class);
    private static final String SIGN= "!@#$%^&*720906";

    public static final Integer expire = SpringUtil.getBean(JwtConfig.class).getExpire();
    /**
     * 生成Token
     */
    public static String generateToken(Map<String,String> map) {
        Calendar instance = Calendar.getInstance();
        instance.add(Calendar.MINUTE, expire);
        Map<String, Object> headerClaims = new HashMap<>();
        headerClaims.put("type","jwt");
        headerClaims.put("sign","hmac256");
        JWTCreator.Builder creator = JWT.create();
        map.forEach(creator::withClaim);
        return creator.withExpiresAt(instance.getTime())
                .withHeader(headerClaims)
                .sign(Algorithm.HMAC256(SIGN));
    }

    /**
     * 验证token
     */
    public static DecodedJWT verifyToken(String token) {
        try{
            return JWT.require(Algorithm.HMAC256(SIGN)).build().verify(token);
        }catch (SignatureVerificationException ex){
            logger.error("无效签名");
        }catch (TokenExpiredException ex){
            logger.error("签名已过期");
        }catch (AlgorithmMismatchException ex){
            logger.error("算法不一致");
        }catch (Exception ex){
            logger.error("校验过程出现异常");
        }
        return null;
    }

    public static Long getUserIdFromToken(String token){
        return JWT.require(Algorithm.HMAC256(SIGN)).build().verify(token).getClaim("userId").asLong();
    }

}
